<?php
class Captcha_model extends CI_Model{
	function add($word,$time){
		$expiration = time()-7200; // Two hour limit
		$this->_remove($expiration);
		
		$data = array(
			'time'			=>$time,
			'word'			=>$word
		);
		
		return $this->db->insert('captcha',$data);
	}
	
	function check($captcha){
		$expiration = time()-7200; // Two hour limit
		$this->_remove($expiration);

		$this->db->where('word',$captcha);
		$query = $this->db->get('captcha');
		if($query->num_rows()>0){			
			
			//Elimino la entrada para que no la vuelva a utilizar
			$this->db->where('word', $captcha);
			$this->db->delete('captcha');
			
			//Elimino la imagen
			$results = $query->result();
			$dir='./captcha/'.$results[0]->time.'.jpg';  
			
			if(file_exists($dir)) 
				unlink($dir);
			return true;
		}
		else
			return false;
	}
	
	function _remove($expiration){
		$this->db->where('time <', $expiration);
		$query = $this->db->get('captcha');
		$results = $query->result();
		for($i=0; $i < $query->num_rows();$i++){
			$dir='./captcha/'.$results[$i]->time.'.jpg';  
			if(file_exists($dir)) 
				unlink($dir);
		}
		
		$this->db->where('time <', $expiration);
		$this->db->delete('captcha');
	}
}